import axios from "axios";
import appConfig from '@/config';
import { getToken } from "./token";

const instance = axios.create({
  timeout: appConfig.API_TIMEOUT,
  headers: appConfig.API_HEADERS,
  // baseURL: 'http://192.168.0.114:9081/',
})

//转成formData格式的参数
// const toFormDataParams = beforeData => {
//   if(!beforeData) return beforeData;
//   const formData = new FormData();
//   for (const key in beforeData) {
//     if (beforeData.hasOwnProperty(key)) formData.append(key, beforeData[key]);
//   };
//   return formData;
// }

instance.interceptors.request.use(config => {
  console.log('post config', config);
  const token = getToken();
  if(token) config.headers[appConfig.TOKEN_NAME] = `${appConfig.TOKEN_PREFIX}${token}`
  return config
}, err => Promise.reject(err))

//该方法晚于请求拦截器执行(注意: 该方法会把请求参数修改成forData格式)
// instance.defaults.transformRequest = data => {
//   return data; //可在此修改请求参数，也可以在请求拦截器中取config.data修改
// }

instance.interceptors.response.use(res => {
  if (res.status === 200) return Promise.resolve(res.data)
  else return Promise.reject(res)
}, err => Promise.reject(err))

export default instance;